/*
 * @Descripttion:
 * @Author: liuxiaoling
 * @Date: 2021-04-03 16:11:05
 * @LastEditors: liuxiaoling
 * @LastEditTime: 2021-04-18 17:46:48
 */
import cityList from '../constants/cityList'
import constant from '../utils/constant'
import addStorageEvent from '../utils/addStorageEvent'

/** 根据 cityCode 获取 city */
export function cityFilter(cityCode) {
  for (let group of cityList) {
    for (let item of group.list) {
      if (item.cityCode === cityCode) {
        return item
      }
    }
  }
  return null
}

/** ID列表拼接为逗号分隔的字符串 */
export function concatIds(idList) {
  if (idList.length === 0) {
    return ''
  }
  let str = ''
  for (const id of idList) {
    str += id + ','
  }

  //去掉最后一个逗号(如果不需要去掉，就不用写)
  if (str.length > 0) {
    str = str.substr(0, str.length - 1)
  }
  return str
}

/** 存储历史位置信息(最多存储10个，超出则从前往后删除) */
export function storageHistoryLocation(address) {
  let locationList = []
  if (localStorage.getItem(constant.STORAGE_HISTORY_LOCATION)) {
    locationList = JSON.parse(localStorage.getItem(constant.STORAGE_HISTORY_LOCATION))
  }
  for (let item of locationList) {
    if (item.id == address.id) {
      return
    }
  }

  // 最多存储10个，超出则从前往后删除（改为: 从后往前）
  if (locationList.length >= 10) {
    locationList.splice(9, locationList.length - 9)
  }
  // locationList.push(address)
  locationList.unshift(address)

  addStorageEvent(1, constant.STORAGE_HISTORY_LOCATION, JSON.stringify(locationList))
}

/** 根据当前日期构造日期列表, 日期倒序
 * @returns  例： 
  [{time: '2021年7月', date: '2021-7'},
  {time: '2021年6月', date: '2021-6'},
  {time: '2021年5月', date: '2021-5'},
  ...]
*/
export function genDatePicker() {
  const start = '2021-06'
  let startDate = new Date(start)
  let endDate = new Date()

  let result = []

  let curr = endDate
  while (curr >= startDate) {
    let year = curr.getFullYear()
    let month = curr.getMonth() + 1
    let item = {
      time: `${year}年${month}月`,
      date: `${year}-${month}`
    }

    result.push(item)
    curr.setMonth(month - 2)
  }
  return result
}
